import re
from core.engine.lazy_load import FLEXIBLE_PATTERN

class ExpressionParser:
    def __init__(self):
        # 全局缓存，存储已解析的表达式及其结果
        self.express_space = {}
        # 用来替换实例中的高级的词汇（意义灵活多变的），随着每个实例更新。
        self.instance_mappings = None


    def parse_expression(self, expression: str) -> list:
        """
        解析表达式，支持括号嵌套和逻辑运算符。
        """
        expr = expression.replace(' ', '')

        # 递归处理自定义映射
        while expr in self.instance_mappings or re.match(FLEXIBLE_PATTERN,expr):
            expr = self.instance_mappings[expr]

        # 检查是否还需要进一步解析（包含运算符或括号）
        if any(op in expr for op in ('&', '|', '!', '(', ')')):
            # 修改正则表达式以支持!运算符
            tokens = re.findall(r'([()|&!])|([^()|&!]+)', expr)
            tokens = [t[0] or t[1] for t in tokens if any(t)]

            output = []
            operators = []

            for token in tokens:
                if token == '(':
                    operators.append(token)
                elif token == ')':
                    while operators and operators[-1] != '(':
                        output.append(operators.pop())
                    operators.pop()  # 弹出左括号
                elif token in ('&', '|', '!'):
                    # 更新优先级规则：! > & > |
                    while operators and operators[-1] != '(' and (
                            (token in ('&', '|') and operators[-1] == '!') or
                            (token == '|' and operators[-1] == '&')):
                        output.append(operators.pop())
                    operators.append(token)
                else:
                    # 递归解析子表达式
                    sub_expr = self.parse_expression(token)
                    output.extend(sub_expr)

            while operators:
                output.append(operators.pop())

            # 缓存解析结果
            self.express_space[expr] = output
            return output
        else:
            # 简单表达式，直接返回
            return [expr]